from flask import request, current_app
from flask_restx import Resource, Namespace, fields
from app.utils.auth import admin_required
from app.services.admin_user_service import AdminUserService
from app.utils.response import success_response, error_response
from app.utils.validators import validate_required_fields
from . import api

# 创建用户命名空间
users_ns = Namespace('users', description='小程序用户管理')

# 定义请求模型
user_status_request = users_ns.model('UserStatusRequest', {
    'status': fields.Integer(required=True, description='用户状态：1正常2待审核3审核失败4封禁5注销')
})

user_search_request = users_ns.model('UserSearchRequest', {
    'page': fields.Integer(description='页码', default=1),
    'per_page': fields.Integer(description='每页数量', default=20),
    'keyword': fields.String(description='搜索关键词'),
    'status': fields.Integer(description='状态筛选'),
    'gender': fields.Integer(description='性别筛选：1男2女'),
    'min_age': fields.Integer(description='最小年龄'),
    'max_age': fields.Integer(description='最大年龄'),
    'city': fields.String(description='城市筛选'),
    'vip_level': fields.Integer(description='VIP等级筛选'),
    'start_date': fields.String(description='注册开始日期'),
    'end_date': fields.String(description='注册结束日期')
})

@users_ns.route('')
class UserListAPI(Resource):
    """用户列表"""
    
    @admin_required
    def get(self, current_admin):
        """获取用户列表"""
        try:
            # 获取查询参数
            page = request.args.get('page', 1, type=int)
            per_page = request.args.get('per_page', 20, type=int)
            keyword = request.args.get('keyword', '')
            status = request.args.get('status', type=int)
            gender = request.args.get('gender', type=int)
            min_age = request.args.get('min_age', type=int)
            max_age = request.args.get('max_age', type=int)
            city = request.args.get('city', '')
            vip_level = request.args.get('vip_level', type=int)
            start_date = request.args.get('start_date', '')
            end_date = request.args.get('end_date', '')
            
            # 构建查询参数
            filters = {
                'keyword': keyword,
                'status': status,
                'gender': gender,
                'min_age': min_age,
                'max_age': max_age,
                'city': city,
                'vip_level': vip_level,
                'start_date': start_date,
                'end_date': end_date
            }
            
            # 获取用户列表
            result = AdminUserService.get_user_list(page, per_page, filters)
            return success_response(result, '获取成功')
            
        except Exception as e:
            current_app.logger.error(f"获取用户列表异常: {str(e)}")
            return error_response(f"获取失败: {str(e)}", 500)


@users_ns.route('/<int:user_id>')
class UserDetailAPI(Resource):
    """用户详情"""
    
    @admin_required
    def get(self, user_id, current_admin):
        """获取用户详情"""
        try:
            user_detail = AdminUserService.get_user_detail(user_id)
            if not user_detail:
                return error_response('用户不存在', 404)
            
            return success_response(user_detail, '获取成功')
        except Exception as e:
            current_app.logger.error(f"获取用户详情异常: {str(e)}")
            return error_response(f"获取失败: {str(e)}", 500)
    
    @admin_required
    def delete(self, user_id, current_admin):
        """删除用户"""
        try:
            success = AdminUserService.delete_user(user_id, current_admin.id)
            if not success:
                return error_response('删除失败，用户不存在', 404)
            
            return success_response(message='删除成功')
        except Exception as e:
            current_app.logger.error(f"删除用户异常: {str(e)}")
            return error_response(f"删除失败: {str(e)}", 500)


@users_ns.route('/<int:user_id>/status')
class UserStatusAPI(Resource):
    """用户状态管理"""
    
    @users_ns.expect(user_status_request)
    @admin_required
    def put(self, user_id, current_admin):
        """更新用户状态"""
        try:
            # 验证必填字段
            is_valid, error_msg = validate_required_fields(['status'])
            if not is_valid:
                return error_response(error_msg, 400)
            
            data = request.get_json()
            status = data.get('status')
            
            # 状态验证
            if status not in [1, 2, 3, 4, 5]:
                return error_response('状态值无效', 400)
            
            user = AdminUserService.update_user_status(user_id, status, current_admin.id)
            if not user:
                return error_response('用户不存在', 404)
            
            return success_response(user, '状态更新成功')
        except Exception as e:
            current_app.logger.error(f"更新用户状态异常: {str(e)}")
            return error_response(f"更新失败: {str(e)}", 500)


@users_ns.route('/export')
class UserExportAPI(Resource):
    """用户数据导出"""
    
    @admin_required
    def get(self, current_admin):
        """导出用户数据"""
        try:
            # 获取查询参数
            filters = {
                'status': request.args.get('status', type=int),
                'gender': request.args.get('gender', type=int),
                'city': request.args.get('city', ''),
                'start_date': request.args.get('start_date', ''),
                'end_date': request.args.get('end_date', '')
            }
            
            export_data = AdminUserService.export_users(filters)
            return success_response(export_data, '导出成功')
        except Exception as e:
            current_app.logger.error(f"导出用户数据异常: {str(e)}")
            return error_response(f"导出失败: {str(e)}", 500)


@users_ns.route('/statistics')
class UserStatisticsAPI(Resource):
    """用户统计"""
    
    @admin_required
    def get(self, current_admin):
        """获取用户统计数据"""
        try:
            stats = AdminUserService.get_user_statistics()
            return success_response(stats, '获取成功')
        except Exception as e:
            current_app.logger.error(f"获取用户统计异常: {str(e)}")
            return error_response(f"获取失败: {str(e)}", 500)


# 将命名空间注册到统一的API实例
api.add_namespace(users_ns, path='/users') 